package com.skytech.component.crawler.excel;


import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by QinYi on 2018/8/27.
 */
public class ExcelTool {
    private Logger logger = LoggerFactory.getLogger(ExcelTool.class);

    private XSSFWorkbook workbook;
    private XSSFSheet sheet;
    private int index = 0;

    private String excelName;

    public ExcelTool(){
        this.workbook = new XSSFWorkbook();
        this.sheet = workbook.createSheet();
    }
    public ExcelTool(String excelName){
        this.workbook = new XSSFWorkbook();
        this.sheet = workbook.createSheet();
        this.excelName = excelName;
    }
    public List<String> print(List<String> list){
        XSSFRow row = sheet.createRow(index);
        for (int i=0;i<list.size();i++){
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(list.get(i));
        }
        index = index+1;
        return list;
    }
    public FileOutputStream getFileOutputStream(String filePath,String fileName){

        FileOutputStream outputStream = null;
        String path = filePath;
        if(!new File(path+"//exportExcel").exists()){
            new File(path+"//exportExcel").mkdir();
        }
        path = filePath+"//exportExcel";
       // String fileName ;
       /* if(StringUtils.isEmpty(excelName)){
            fileName = fileName;
        }else{
            fileName = excelName+"-"+fileName;
        }*/
        try {
            outputStream = new FileOutputStream(path+"//excel-"+ fileName+".xlsx",true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream;
    }
    public void downloadExcel(String filePath,String fileName){
        FileOutputStream outputStream = getFileOutputStream(filePath,fileName);
        try {
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            logger.info("excel导出结束");
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

    }

}
